package com.ac.api.equipment.controller;

import com.ac.api.process_task.entity.ProcessTask;
import com.ac.api.process_task.service.ProcessTaskService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.RequestMapping;
import com.base.annotation.SysLog;
import org.springframework.web.bind.annotation.RestController;
import com.base.helper.BaseController;
import com.base.helper.Result;
import com.ac.api.equipment.entity.Equipment;
import com.ac.api.equipment.service.EquipmentService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 生产设备信息表 前端控制器
 * </p>
 *
 * @author dc
 * @since 2025-06-11
 */
@Api(tags = "Equipment")
@RestController
@RequestMapping("/equipment")
public class EquipmentController extends BaseController {

        private static final Logger       LOG = LoggerFactory.getLogger(EquipmentController.class);
        @Autowired
        private              EquipmentService entityService;
        @Autowired
        private ProcessTaskService processTaskService;
        @SysLog(action = "findByPage", value = "分页查询设备")
        @ApiOperation(value = "分页查询设备", notes = "分页查询设备")
        @RequestMapping(method = RequestMethod.GET)
        @ApiImplicitParams({@ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
                @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")})
        public Result<IPage<Equipment>> findByPage(final Equipment example, final Page page) {
            IPage<Equipment>        records    = entityService.page(example,page);
            return new Result(true, records);
        }
        //根据状态status分页查询设备
         @SysLog(action = "findStatusByPage", value = "分页查询设备")
         @ApiOperation(value = "根据状态status分页查询设备", notes = "根据状态status分页查询设备")
          @RequestMapping(value = "status", method = RequestMethod.GET)
         @ApiImplicitParams({@ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
                @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query"),
                @ApiImplicitParam(name = "status", value = "设备状态", paramType = "query")})
         public Result<IPage<Equipment>> findStatusByPage(@RequestParam String status, final Page page) {
            QueryWrapper<Equipment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status",status);
            IPage<Equipment>        records    = entityService.page(page,queryWrapper);
            return new Result(true, records);
        }

        @SysLog(action = "delete", value = "删除设备")
        @ApiOperation(value = "删除设备")
        @RequestMapping(value = "{id}", method = {RequestMethod.DELETE})
        @ApiImplicitParam(name = "id", value = "设备ID", required = true, paramType = "path")
        public Result delete(@PathVariable final Integer id) {
            try {
                entityService.removeById(id);
                return new Result(true, "成功删除设备", null);
            } catch (DataIntegrityViolationException e) {
                LOG.error("删除设备失败", e);
                return new Result(false, "删除设备失败", "该设备不能删除，存在其他关联数据");
            } catch (Exception e) {
                LOG.error("删除设备失败", e);
                return new Result(false, "删除设备失败", e.getMessage());
            }
        }

        @SysLog(action = "one", value = "查询单个设备")
        @ApiOperation(value = "查询单个设备")
        @RequestMapping(value = "{id}", method = {RequestMethod.GET})
        @ApiImplicitParam(name = "id", value = "设备ID", required = true, paramType = "path")
        public Result one(@PathVariable final Integer id) {
            try {
                Equipment entity = entityService.getById(id);
                return new Result(true, entity);
            } catch (Exception e) {
                LOG.error("查询单个设备失败", e);
                return new Result(false, new Equipment());
            }
        }

        @SysLog(action = "add", value = "添加设备")
        @ApiOperation(value = "添加设备")
        @RequestMapping(method = {RequestMethod.POST})
        public Result add(@Valid @RequestBody final Equipment entity, final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "保存设备失败", errorMsg, map);
                } else {
                    entityService.save(entity);
                    return new Result(true, "成功保存设备", null);
                }
            } catch (Exception e) {
                LOG.error("添加设备失败", e);
                return new Result(false, "保存设备失败", e.getMessage());
            }
        }

        @SysLog(action = "update", value = "修改设备")
        @ApiOperation(value = "修改设备")
        @RequestMapping(method = {RequestMethod.PUT})
        public Result update(@Valid @RequestBody final Equipment entity, final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "修改设备失败", errorMsg, map);
                } else {
                    if (null == entity.getEquipmentId()) {
                         throw new RuntimeException("id不能为空");
                    }
                    entityService.updateById(entity);
                    return new Result(true, "成功修改设备", null);
                }
            } catch (Exception e) {
                LOG.error("修改设备失败", e);
                return new Result(false, "修改设备失败", e.getMessage());
            }
        }

        @ApiOperation(value = "全部设备")
        @RequestMapping(value = "all", method = RequestMethod.GET)
        public Result<List<Equipment>> all(Equipment example) {
            List<Equipment> entitys = entityService.list(example);
            if (null != entitys) {
                return new Result<>(true, entitys);
            }
            return new Result<>(true, Collections.emptyList());
        }

        //将设备加入工序区
        @ApiOperation(value = "将设备加入工序区")
        @PostMapping("/addToProcessTask")
        public Result addToProcessTask(@RequestParam Integer id,Integer processTaskId) {
            try {
                Equipment entity = entityService.getById(id);
                if(entity.getStatus().equals("停机")){
                    entity.setProductionTaskId(processTaskId);
                    entityService.updateById(entity);
                    return new Result<>(true, "成功将设备加入工序区", null);
                }
                else return new Result<>(false, "设备正处于维修或已在运行中，无法加入工序区", null);
            } catch (Exception e) {
                LOG.error("将设备加入工序区失败", e);
                return new Result<>(false, "将设备加入工序区失败", e.getMessage());
            }
        }
        @ApiOperation(value = "将设备从工序区移出")
        @PostMapping("/removeFromProcessTask")
        public Result removeFromProcessTask(@RequestParam Integer id) {
            try {
                Equipment entity = entityService.getById(id);
                entity.setProductionTaskId(0);
                entity.setStatus("停机");
                entityService.updateById(entity);
                return new Result<>(true, "成功将设备从工序区移出", null);
            } catch (Exception e) {
                LOG.error("将设备从工序区移出失败", e);
                return new Result<>(false, "将设备从工序区移出失败", e.getMessage());
            }
        }
        //设置设备故障
        @ApiOperation(value = "设置设备故障")
        @PostMapping("/setFault")
        public Result setFault(@RequestParam Integer id) {
            try {
                Equipment entity = entityService.getById(id);
                entity.setStatus("维修");
                entity.setProductionTaskId(0);
                entityService.updateById(entity);
                return new Result<>(true, "成功设置设备故障", null);
            } catch (Exception e) {
                LOG.error("设置设备故障失败", e);
                return new Result<>(false, "设置设备故障失败", e.getMessage());
            }
        }
        //获取空闲设备列表
        @ApiOperation(value = "获取空闲设备列表(未加入工序区的)")
        @GetMapping("/free")
        public Result<List<Equipment>> free() {
            try {
                List<Equipment> entitys = entityService.list(new QueryWrapper<Equipment>().eq("production_task_id",0)
                        .eq("status","停机"));
                if (null != entitys) {
                    return new Result<>(true, entitys);
                }
                return new Result<>(true, Collections.emptyList());
            } catch (Exception e) {
                LOG.error("获取空闲设备列表失败", e);
                return new Result<>(false, "获取空闲设备列表失败", e.getMessage());
            }
        }
        //设备名搜索
        @ApiOperation(value = "设备名搜索")
        @GetMapping("/search")
        public Result<Page<Equipment>> search(@RequestParam String name, final Page page) {
            try {
                Page<Equipment> entitys = entityService.page(page,new QueryWrapper<Equipment>().like("name",name));
                if (null != entitys) {
                    return new Result<>(true, entitys);
                }
                return new Result<>(true);
            } catch (Exception e) {
                LOG.error("设备名搜索失败", e);
                return new Result<>(false, "设备名搜索失败", e.getMessage());
            }
        }
        @ApiOperation(value = "设备名状态同时查询")
         @GetMapping("/searchAnd")
    public Result<Page<Equipment>> searchAnd(@RequestParam String name, @RequestParam String status, final Page page){
            try {
                Page<Equipment> entitys = entityService.page(page,new QueryWrapper<Equipment>().like("name",name).eq("status",status));
                if (null != entitys) {
                    return new Result<>(true, entitys);
                }
                return new Result<>(true);
            } catch (Exception e) {
                LOG.error("设备名搜索失败", e);
                return new Result<>(false, "设备名搜索失败", e.getMessage());
            }
        }
}

